package com.example.demo.config;

import com.example.demo.common.TokenIsNullException;
import com.example.demo.common.TokenValidateException;
import com.example.demo.utils.JWTUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String logintoken = request.getHeader("LOGINTOKEN");
        //如果token为空
        if (StringUtils.isBlank(logintoken)){
            throw new TokenIsNullException("请登录");
        }
        //校验Token
        String sub = JWTUtils.validateToken(logintoken);
        if (StringUtils.isBlank(sub)){
            throw new TokenValidateException("token校验失败");
        }

        //更新token有效期(生产新token)
        if (JWTUtils.refreshToken(logintoken)){
            String token = JWTUtils.createToken(sub);
            response.setHeader(JWTUtils.header,token);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
